#!env python
# -*- encoding: utf-8 -*-

import gettalkbox
from dbhelper import DbHelper
from xml.dom.minidom import parse
import xml.dom.minidom
import time

#Tstdb=None

astring='''
<TalkBox>
  <status>fail</status>
  <message>User  not found</message>
  <msgcode>105</msgcode>
</TalkBox>
'''

bstring='''<TalkBox>
  <status>success</status>
  <user>
    <tbId>9509507</tbId>
    <username>firear</username>
    <displayName>firear </displayName>
  </user>
</TalkBox>'''

def parsesearch(xmlstring):
    DOMTree = xml.dom.minidom.parseString(xmlstring)
    TalkBox = DOMTree.documentElement
    status = TalkBox.getElementsByTagName("status")
    statusresult = status[0].childNodes[0].data
    if 'fail' == statusresult:
        return -1
    else:
        user = TalkBox.getElementsByTagName("user")
        tbId = user[0].getElementsByTagName("tbId")
        tbvalue = tbId[0].childNodes[0].data
        return int(tbvalue)


def doget():
    global Tstdb
    while 1:
        emails = Tstdb.getEmails(10)
        if(len(emails) == 0):
            break
        for email in emails:
            profile=''
            searchresult = gettalkbox.search(email)
            tbId = parsesearch(searchresult)
            if tbId != -1:
                profile = gettalkbox.getProfile(tbId)
            Tstdb.insertALine(tbId, profile, email, searchresult)
        Tstdb.commit()

if __name__ == "__main__":
    global Tstdb
    Tstdb = DbHelper('talkbox.db')
    doget()
